package com.flaremars.picker.utils.http.newhttp;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by FlareMars on 2016/1/28.
 */
public enum HttpHelper {
    INSTANCE;

    private OkHttpClient client = new OkHttpClient.Builder().build();

    public Call get(String url,Callback callback) {
        Request request = new Request.Builder().
                url(url).
                build();
        Call call = client.newCall(request);
        call.enqueue(callback);
        return call;
    }

    public Call get(String url,Map<String,String> params,Callback callback) {
        return get(url + mapToUrlParamsStr(params), callback);
    }

    public Call post(String url,Map<String,String> params,Callback callback) {
        Call call = client.newCall(buildPostRequest(url,params));
        call.enqueue(callback);
        return call;
    }

    public String post(String url,Map<String,String> params) throws IOException {
        Call call = client.newCall(buildPostRequest(url,params));
        return call.execute().body().string();
    }

    private Request buildPostRequest(String url, Map<String,String> params) {
        if (params == null) {
            params = new HashMap<>(0);
        }
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String,String> entry : params.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        RequestBody requestBody = builder.build();
        return new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
    }

    private String mapToUrlParamsStr(Map<String,String> params) {
        StringBuilder sb = new StringBuilder("?");
        for (Map.Entry<String,String> entry : params.entrySet()) {
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            sb.append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
